package mfuny.ggongal.admin.http;

import mfuny.ggongal.admin.debug.Debug;
import mfuny.ggongal.admin.https.GGDecoder;
import mfuny.ggongal.admin.https.GGEncoder;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class HttpGameDecoder {
	
	@SuppressWarnings("unchecked")
	public String receiveDecode(String enStr) throws Exception {
		String deStr = GGDecoder.decode(enStr);
		
		JSONObject paramJson = (JSONObject)JSONValue.parse(deStr);
		JSONObject resultJson = new JSONObject();
		
		HttpGame game = new HttpGame();
		
		//게임 시작.
		if(paramJson.get("tag").equals("game_start")) {
			try {
				resultJson = game.game_start(paramJson);
			} catch(Exception e) {
				Debug.toDebugFile(e, (String)paramJson.get("tag"));
			}
		}
		
		//게임 끝.
		else if(paramJson.get("tag").equals("game_end")) {
			try {
				paramJson.put("no", paramJson.get("play_no"));
				resultJson = game.game_end(paramJson);
			} catch ( Exception e) {
				Debug.toDebugFile(e, (String)paramJson.get("tag"));
			}
		}
		
		//경품 받을지 여부 결정.
		else if(paramJson.get("tag").equals("game_setReceive")) {
			try {
				int result = game.game_setReceive(
						Integer.parseInt((String)paramJson.get("mygift_no")), 
						Integer.parseInt((String)paramJson.get("receive"))
				);
				resultJson.put("responseCode", result);
			} catch ( Exception e) {
				Debug.toDebugFile(e, (String)paramJson.get("tag"));
				resultJson.put("responseCode", -1);
			}
		}
		
		//게임 끝나고 랭킹만..
		else if(paramJson.get("tag").equals("game_getRank")) {
			try{
				resultJson = game.game_getRank(paramJson);
			} catch(Exception e) {
				Debug.toDebugFile(e, (String)paramJson.get("tag"));
			}
		}
		
		//암호화 되어있으나 tag가 없을때.
		else {
			Debug.toDebugFile("tag 없음 - "+(String)paramJson.get("tag"));
		}
		
		return GGEncoder.encodeForJson(resultJson);
	}
}
